/*
 * Copyright (C) 2023 Kevin Buzeau
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.buzbuz.smartautoclicker.core.base.migrations


/** Format a foreign key to get the same index table name as the one generated by room.*/
internal fun SQLiteColumn.ForeignKey.formatAsRoomDefaultIndexName(tableName: String, indexName: String?): String =
    if (indexName.isNullOrEmpty()) "index_${tableName}_${name}"
    else indexName

/**
 * Format as an optional clause for a SQLite statement.
 * If this string is null or empty, returns an empty string.
 *
 * If not, produce the following output:
 *  WHERE myString
 */
internal fun String?.formatAsOptionalClause(): String =
    if (isNullOrEmpty()) "" else "$this"

/**
 * Format a list of values for a SQLite statement, appending correctly the coma between values when needed.
 * Output will have the following formats:
 *   - Zero: ""
 *   - One: "value_1"
 *   - Two or more: "value_1, value_2, value_3, ..."
 */
internal fun Collection<Any>.formatAsSQLiteList(): String =
    buildString { this@formatAsSQLiteList.forEach(::appendAsSQLiteListElement) }


/**
 * Format a list of column/value pair as a list for a SQLite UPDATE statement.
 * Output will have the following formats:
 *   - Zero: ""
 *   - One: "`column_1` = value_1"
 *   - Two or more: "`column_1` = value_1, `column_2` = value_2, `column_3` = value_3, ..."
 */
internal fun Collection<Pair<String, String>>.formatAsSQLiteUpdateList(): String =
    buildString {
        this@formatAsSQLiteUpdateList.forEach { (columnName, columnValue) ->
            if (isNotEmpty()) append(" ,")
            append("`$columnName` = $columnValue")
        }
    }

/**
 * Format a primary key column for a SQLite create table statement.
 * Output will have the following format:
 *   `columnName` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
 */
internal fun SQLiteColumn.PrimaryKey.formatAsSQLiteCreateTablePrimaryKeyColumn(): String =
    "`$name` $typeSQLLite PRIMARY KEY AUTOINCREMENT NOT NULL"

/**
 * Format a list of columns for a SQLite create table statement.
 * The primary key must not be included in the list and must have been handled separately. (see
 * [formatAsSQLiteCreateTablePrimaryKeyColumn]).
 *
 * Output will have the following format:
 *   `column1` INTEGER NOT NULL,
 *   `column2` TEXT,
 *   FOREIGN KEY(`column1`) REFERENCES `anotherTable`(`anotherColumn`) ON UPDATE CASCADE ON DELETE NO ACTION
 */
internal fun Collection<SQLiteColumn<*>>.formatAsSQLiteCreateTableColumnList(): String =
    buildString {
        val foreignKeys = mutableListOf<SQLiteColumn.ForeignKey>()

        this@formatAsSQLiteCreateTableColumnList.forEach { column ->
            if (column is SQLiteColumn.PrimaryKey)
                throw IllegalArgumentException("Primary key column not supported by formatAsSQLiteCreateTableColumnList")

            appendAsCreateTableColumn(column)
            if (column is SQLiteColumn.ForeignKey) foreignKeys.add(column)
        }

        foreignKeys.forEach(::appendAsSQLiteForeignKey)
    }

/**
 * Format a foreign key to the StringBuilder containing the SQLite column list representation for a create table.
 * As a foreign key must reference another column, it is never the first element, so always add " ," at the beginning.
 */
private fun SQLiteColumn.ForeignKey.formatAsSQLiteCreateTableForeignKey(): String =
    "FOREIGN KEY(`$name`) REFERENCES `$referencedTable`(`$referencedColumn`)" +
            " ON UPDATE $updateActionSQLite ON DELETE $deleteActionSQLite"

/**
 * Append a foreign key to the StringBuilder.
 * As a foreign key must reference another column, it is never the first element, so always add " ," at the beginning.
 */
private fun StringBuilder.appendAsSQLiteForeignKey(foreignKey: SQLiteColumn.ForeignKey) = append(
    """,
            ${foreignKey.formatAsSQLiteCreateTableForeignKey()}
    """.trimIndent()
)

/**
 * Append a new element to the StringBuilder containing the SQLite list representation.
 * If it's not the first, append ", " before it.
 */
private fun StringBuilder.appendAsSQLiteListElement(element: Any): StringBuilder =
    if (isNotEmpty()) append(", $element") else append("$element")

/**
 * Append a new column to the StringBuilder containing the SQLite column list representation for a create table.
 * If it's not the first column, append ", " before it.
 */
private fun StringBuilder.appendAsCreateTableColumn(column: SQLiteColumn<*>): StringBuilder {
    if (isNotEmpty()) append(", ")
    append("`${column.name}` ${column.typeSQLLite}")
    if (column.isNotNull) {
        append(" NOT NULL")
        if (column is SQLiteColumn.Default && column.defaultValue != null) append(" DEFAULT ${column.defaultValue}")
    }

    return this
}
